#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <pthread.h>
#include <unistd.h>
#include "randomize.h"
#include "table.h"




const unsigned int CYCLE_NUM = 2500;
const unsigned int TABLE_SIZE = 257;
const int HILO_READ = 10;
const int HILO_WRITE = 10;
// variable global compartida

void table_read(void);
void table_write(void);

 
int dummy = 42;
table tbl = NULL;


int
main(void)
{
  

	
	pthread_t hilo[HILO_READ];
	pthread_t hilo2[HILO_WRITE];
	int i=0;
	
	tbl = table_create(TABLE_SIZE);
	randomize();
        

      
	printf("Comienzo\n");
	#ifdef __DEBUG
	printf("Debugging activado\n");
	sleep(2);
	#endif


	for (i=0;i<HILO_READ;i++)
	{
		pthread_create(&hilo[i], NULL,(void *) &table_read,  NULL);

	}

	for (i=0;i<HILO_WRITE;i++)
	{
		pthread_create(&hilo2[i], NULL,(void *) &table_write,  NULL);

	}

	for (i=0;i<HILO_WRITE;i++)
	{
		
		pthread_join(hilo2[i], NULL);

	}

	for (i=0;i<HILO_READ;i++)
	{
		pthread_join(hilo[i], NULL);

	}

	
	
	printf("Fin\n");

	tbl = table_destroy(tbl);

	return 0;
}
void table_read(void)
{
  unsigned int idx;
  unsigned int cycle = 0;
 

  for(cycle=0; cycle<CYCLE_NUM; cycle++) 
	{
		idx = rand()%TABLE_SIZE;
		sched_yield();
		if (table_getted(tbl, idx))
		{
			printf("Ciclo %d, devuelve lugar %d\n", cycle, idx);
		}
		
	}
}

void table_write(void)
{
  unsigned int idx;
  unsigned int cycle = 0;

  for(cycle=0; cycle<CYCLE_NUM; cycle++) 
	{
		idx = table_alloc(tbl, &dummy);
		yield();
		if (idx==table_size(tbl)) 
		{
			printf("Ciclo %d, tabla llena\n", cycle);
			yield();
		} 
		else 
		{
			printf("Ciclo %d, obtiene lugar %d\n",cycle, idx);
			
		}
	}
}
